﻿using System;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using EPiServer.Community.Blog;
using EPiServer.Find;
using EPiServer.Find.Helpers.Text;
using log4net;

namespace JoelAbrahamsson.Web.Controllers
{
    public class RelatedEntriesController : Controller
    {
        IClient client;
        private ILog errorLog;

        public RelatedEntriesController(IClient client, ILog errorLog)
        {
            this.client = client;
            this.errorLog = errorLog;
        }

        public ActionResult Index(Entry entry)
        {
            IQueriedSearch<Entry> query = client.Search<Entry>()
                .MoreLike(entry.Content.StripHtml());

            foreach (var category in entry.Categories)
            {
                query = query.BoostMatching(x => x.Categories.MatchContained(c => c.ID, category.ID), 2.5);
            }

            var relatedEntries = query
                .Filter(x => !x.ID.Match(entry.ID))
                .Select(x => x.ID)
                .Take(3)
                .StaticallyCacheFor(TimeSpan.FromHours(24))
                .GetResult()
                .Select(x => BlogHandler.GetEntry(x));

            if (relatedEntries.Count() == 0)
                return new EmptyResult();

            return View(relatedEntries);
        }
    }
}
